<template>
  <el-form-item prop="timer" label="图片的切换时间">
    <el-input-number
      v-model="optionModel.timer"
      :min="0"
      :step="1"
      class="hide-spin-button"
      style="width: 100%"
    >
    </el-input-number>
  </el-form-item>
</template>

<script>
import { GET_IMAGE_RESOURCE_LIST, GET_IMAGE_RESOURCE_LIST_RESULT } from '@/designer/event'

export default {
  name: 'TimerEditor',
  props: {
    designer: Object,
    selectedWidget: Object,
    optionModel: Object
  },
  data() {
    return {
      timer: null,
      imageList: []
    }
  },
  watch: {
    'optionModel.timer': {
      deepth: true,
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          if (this.timer) {
            clearInterval(this.timer)
          }
          this.timer = setInterval(this.setPngCurrentId, newVal)
        }
      }
    }
  },
  created() {},
  mounted() {
    this.$emitter.on(GET_IMAGE_RESOURCE_LIST_RESULT, (list) => {
      this.imageList = list
    })
    this.$emitter.emit(GET_IMAGE_RESOURCE_LIST)

    if (this.optionModel.timer) {
      this.timer = setInterval(this.setPngCurrentId, this.optionModel.timer)
    }
  },
  methods: {
    getPngIdNum(pngId) {
      let num = parseInt(pngId.replace(/P/g, ''), 10)
      if (isNaN(num)) {
        num = 0
      }
      return num
    },
    setPngCurrentId() {
      const currentIdNum = this.getPngIdNum(this.optionModel.pngCurrentId)
      const startIdNum = this.getPngIdNum(this.optionModel.pngStartId)
      let nextIdNum = currentIdNum + 1
      if (nextIdNum >= this.optionModel.pngSize + currentIdNum - 1) {
        nextIdNum = startIdNum
      }

      if (nextIdNum > this.imageList.length) {
        nextIdNum = startIdNum
      }

      this.optionModel.pngCurrentId = `P${nextIdNum}.png`
    }
  }
}
</script>

<style scoped></style>
